package hg.framework.web.handler;

import hg.framework.web.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Iterator;

/***
 * 全局异常处理
 * <p>子类使用时，需继承此类</p>
 * @author hgSuper
 * @date 2020-06-24
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler{

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleBodyValidException(MethodArgumentNotValidException ex) {
        log.error("handleBodyValidException(),参数绑定异常 ex = {}", ex.getMessage(), ex);
        return handleParamNotValid(ex.getBindingResult());
    }

    @ExceptionHandler({ org.springframework.validation.BindException.class})
    public R handleBodyValidException(org.springframework.validation.BindException ex) {
        log.error("handleBodyValidException(),参数绑定异常 ex = {}", ex.getMessage(), ex);
        return handleParamNotValid(ex.getBindingResult());
    }

    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    public R handleGlobalException(Exception e) {
        log.error("handleGlobalException(),全局异常处理 e.class={},e.msg:{}", e.getClass(), e.getMessage(), e);
        return R.failed("服务繁忙，请稍后再试");
    }

    /**
     * 入参验证失败
     * @param bindingResult
     * @return
     */
    private R handleParamNotValid(BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder();
        Iterator var2 = bindingResult.getAllErrors().iterator();
        ObjectError error = null;
        while(var2.hasNext()) {
            error = (ObjectError)var2.next();
            sb.append("[").append(error.getDefaultMessage()).append("] ");
        }
        return R.failed(sb.toString());
    }
}
